<template>
  <div class="home-page">
    <!-- 网站标题和介绍 -->
    <div class="hero-section">
      <div class="hero-content">
        <h1 class="hero-title">
          <span class="title-main">一句话</span>
          <span class="title-icon">🤖</span>
          <span class="title-main">呈所想</span>
        </h1>
        <p class="hero-subtitle">与 AI 对话轻松创建应用和网站</p>
        
        <!-- 用户提示词输入框 -->
        <div class="prompt-input-section">
          <a-textarea
            v-model:value="userPrompt"
            :rows="4"
            placeholder="使用 NoCode 创建一个高效的小工具，帮我计算......"
            class="prompt-textarea"
            :maxlength="500"
            show-count
          />
          <div class="input-actions">
            <div class="action-buttons">
              <a-button type="text" size="small">
                <FileOutlined />
                上传
              </a-button>
              <a-button type="text" size="small">
                <ThunderboltOutlined />
                优化
              </a-button>
            </div>
            <a-button 
              type="primary" 
              size="large" 
              :loading="createLoading"
              @click="handleCreateApp"
              :disabled="!userPrompt.trim()"
              class="create-button"
            >
              <ArrowUpOutlined />
            </a-button>
          </div>
        </div>

        <!-- 快捷模板 -->
        <div class="template-buttons">
          <a-button 
            v-for="template in templates" 
            :key="template.name"
            @click="selectTemplate(template)"
            class="template-btn"
          >
            {{ template.name }}
          </a-button>
        </div>
      </div>
    </div>

    <!-- 我的作品 -->
    <div class="section my-apps-section">
      <div class="section-header">
        <h2>我的作品</h2>
        <a-button type="link" @click="loadMyApps" :loading="myAppsLoading">
          刷新
        </a-button>
      </div>
      
      <div v-if="myApps.length === 0 && !myAppsLoading" class="empty-state">
        <a-empty description="还没有创建任何应用，快来创建第一个吧！" />
      </div>
      
      <div v-else class="apps-grid">
        <div 
          v-for="app in myApps" 
          :key="app.id"
          class="app-card"
          @click="openApp(app)"
        >
          <div class="app-cover">
            <img v-if="app.cover" :src="app.cover" :alt="app.appName" />
            <div v-else class="default-cover">
              <AppstoreOutlined />
            </div>
          </div>
          <div class="app-info">
            <h3 class="app-title">{{ app.appName || '未命名应用' }}</h3>
            <p class="app-time">创建于 {{ formatTime(app.createTime) }}</p>
          </div>
          <div class="app-actions" @click.stop>
            <a-dropdown>
              <a-button type="text" size="small">
                <EllipsisOutlined />
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="editApp(app)">
                    <EditOutlined />
                    编辑
                  </a-menu-item>
                  <a-menu-item @click="deleteApp(app)" danger>
                    <DeleteOutlined />
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
        </div>
      </div>
      
      <div v-if="myApps.length > 0" class="pagination-wrapper">
        <a-pagination
          v-model:current="myAppsPagination.current"
          v-model:page-size="myAppsPagination.pageSize"
          :total="myAppsPagination.total"
          :show-size-changer="false"
          :show-quick-jumper="true"
          @change="loadMyApps"
        />
      </div>
    </div>

    <!-- 精选案例 -->
    <div class="section featured-apps-section">
      <div class="section-header">
        <h2>精选案例</h2>
        <a-button type="link" @click="loadFeaturedApps" :loading="featuredAppsLoading">
          刷新
        </a-button>
      </div>
      
      <div class="apps-grid">
        <div 
          v-for="app in featuredApps" 
          :key="app.id"
          class="app-card featured-card"
          @click="openApp(app)"
        >
          <div class="app-cover">
            <img v-if="app.cover" :src="app.cover" :alt="app.appName" />
            <div v-else class="default-cover">
              <AppstoreOutlined />
            </div>
          </div>
          <div class="app-info">
            <h3 class="app-title">{{ app.appName || '未命名应用' }}</h3>
            <div class="app-meta">
              <span class="app-author">{{ app.user?.userName || 'NoCode 官方' }}</span>
              <span class="app-time">{{ formatTime(app.createTime) }}</span>
            </div>
          </div>
          <div class="featured-badge">精选</div>
        </div>
      </div>
      
      <div v-if="featuredApps.length > 0" class="pagination-wrapper">
        <a-pagination
          v-model:current="featuredAppsPagination.current"
          v-model:page-size="featuredAppsPagination.pageSize"
          :total="featuredAppsPagination.total"
          :show-size-changer="false"
          :show-quick-jumper="true"
          @change="loadFeaturedApps"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { 
  FileOutlined, 
  ThunderboltOutlined, 
  ArrowUpOutlined,
  AppstoreOutlined,
  EllipsisOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/loginUser'
import { 
  addApp, 
  listMyAppVoByPage, 
  listGoodAppVoByPage, 
  deleteApp as deleteAppApi 
} from '@/api/appController'
import dayjs from 'dayjs'

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 用户输入
const userPrompt = ref('')
const createLoading = ref(false)

// 我的应用
const myApps = ref<API.AppVO[]>([])
const myAppsLoading = ref(false)
const myAppsPagination = ref({
  current: 1,
  pageSize: 6,
  total: 0
})

// 精选应用
const featuredApps = ref<API.AppVO[]>([])
const featuredAppsLoading = ref(false)
const featuredAppsPagination = ref({
  current: 1,
  pageSize: 8,
  total: 0
})

// 模板数据
const templates = ref([
  { name: '波普风电商页面', prompt: '创建一个波普风格的电商页面，包含商品展示和购物车功能' },
  { name: '企业网站', prompt: '创建一个专业的企业官网，包含公司介绍、产品展示和联系方式' },
  { name: '电商运营后台', prompt: '创建一个电商运营后台管理系统，包含订单管理、商品管理等功能' },
  { name: '暗黑话题社区', prompt: '创建一个暗黑风格的话题讨论社区，支持发帖、评论和用户互动' }
])

// 是否已登录
const isLoggedIn = computed(() => !!loginUserStore.loginUser.id)

// 创建应用
const handleCreateApp = async () => {
  if (!isLoggedIn.value) {
    message.warning('请先登录')
    router.push('/user/login')
    return
  }

  if (!userPrompt.value.trim()) {
    message.warning('请输入应用描述')
    return
  }

  createLoading.value = true
  try {
    const res = await addApp({ initPrompt: userPrompt.value.trim() })
    if (res.data.code === 0) {
      message.success('应用创建成功，正在跳转...')
      // 跳转到对话页面
      router.push(`/app/chat/${res.data.data}`)
    } else {
      message.error('创建失败：' + res.data.message)
    }
  } catch (error) {
    message.error('创建失败，请重试')
  } finally {
    createLoading.value = false
  }
}

// 选择模板
const selectTemplate = (template: any) => {
  userPrompt.value = template.prompt
}

// 加载我的应用
const loadMyApps = async () => {
  if (!isLoggedIn.value) return
  
  myAppsLoading.value = true
  try {
    const res = await listMyAppVoByPage({
      pageNum: myAppsPagination.value.current,
      pageSize: myAppsPagination.value.pageSize
    })
    if (res.data.code === 0) {
      myApps.value = res.data.data?.records || []
      myAppsPagination.value.total = res.data.data?.totalRow || 0
    } else {
      message.error('加载失败：' + res.data.message)
    }
  } catch (error) {
    message.error('加载失败')
  } finally {
    myAppsLoading.value = false
  }
}

// 加载精选应用
const loadFeaturedApps = async () => {
  featuredAppsLoading.value = true
  try {
    const res = await listGoodAppVoByPage({
      pageNum: featuredAppsPagination.value.current,
      pageSize: featuredAppsPagination.value.pageSize
    })
    if (res.data.code === 0) {
      featuredApps.value = res.data.data?.records || []
      featuredAppsPagination.value.total = res.data.data?.totalRow || 0
    } else {
      message.error('加载失败：' + res.data.message)
    }
  } catch (error) {
    message.error('加载失败')
  } finally {
    featuredAppsLoading.value = false
  }
}

// 打开应用
const openApp = (app: API.AppVO) => {
  router.push(`/app/chat/${app.id}`)
}

// 编辑应用
const editApp = (app: API.AppVO) => {
  router.push(`/app/edit/${app.id}`)
}

// 删除应用
const deleteApp = (app: API.AppVO) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除应用"${app.appName}"吗？此操作不可恢复。`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        const res = await deleteAppApi({ id: app.id })
        if (res.data.code === 0) {
          message.success('删除成功')
          loadMyApps()
        } else {
          message.error('删除失败：' + res.data.message)
        }
      } catch (error) {
        message.error('删除失败')
      }
    }
  })
}

// 格式化时间
const formatTime = (time?: string) => {
  if (!time) return ''
  return dayjs(time).format('MM-DD')
}

onMounted(() => {
  loadFeaturedApps()
  if (isLoggedIn.value) {
    loadMyApps()
  }
})
</script>

<style scoped>
.home-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.hero-section {
  padding: 80px 24px 120px;
  text-align: center;
  color: white;
}

.hero-content {
  max-width: 800px;
  margin: 0 auto;
}

.hero-title {
  font-size: 48px;
  font-weight: bold;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.title-main {
  color: white;
}

.title-icon {
  font-size: 56px;
  background: linear-gradient(45deg, #00d4ff, #00ff88);
  border-radius: 50%;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.hero-subtitle {
  font-size: 18px;
  margin-bottom: 48px;
  opacity: 0.9;
}

.prompt-input-section {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  margin-bottom: 32px;
}

.prompt-textarea {
  border: none;
  box-shadow: none;
  font-size: 16px;
  resize: none;
}

.prompt-textarea:focus {
  border: none;
  box-shadow: none;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.create-button {
  border-radius: 50%;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.template-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  flex-wrap: wrap;
}

.template-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  border-radius: 20px;
  backdrop-filter: blur(10px);
}

.template-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  color: white;
}

.section {
  background: white;
  padding: 48px 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
}

.section-header h2 {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.apps-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.app-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.app-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.featured-card {
  border: 2px solid #1890ff;
}

.app-cover {
  height: 160px;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.app-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-cover {
  font-size: 48px;
  color: #d9d9d9;
}

.app-info {
  padding: 16px;
}

.app-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.app-time {
  color: #999;
  font-size: 12px;
  margin: 0;
}

.app-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.app-author {
  font-weight: 500;
  color: #666;
}

.app-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 6px;
  backdrop-filter: blur(4px);
}

.featured-badge {
  position: absolute;
  top: 12px;
  left: 12px;
  background: #1890ff;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

.my-apps-section {
  background: #fafafa;
}

@media (max-width: 768px) {
  .hero-title {
    font-size: 32px;
  }
  
  .title-icon {
    width: 60px;
    height: 60px;
    font-size: 42px;
  }
  
  .apps-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
  }
  
  .section {
    padding: 32px 16px;
  }
  
  .template-buttons {
    flex-direction: column;
    align-items: center;
  }
}
</style>
